﻿using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Wodsoft.Net.Sockets;

public class SocketThread
{

	private string host = "127.0.0.1";
	private int port = 8000;
	private MemoryStream readStream = new MemoryStream (1024);

	public void run ()
	{
		IPEndPoint address = new IPEndPoint (IPAddress.Parse (host), port);

        TCPClient client = new TCPClient();
        client.ReceiveCompleted += client_ReceiveCompleted;
        client.Connect(address);
	}

    void client_ReceiveCompleted(object sender, SocketEventArgs e)
    {
        if(e.Operation == SocketAsyncOperation.Receive)
        {
            byte[] data = e.Data;
            int length = e.DataLength;

            byte[] cmdBytes = new byte[2];
            cmdBytes[0] = data[0];
            cmdBytes[1] = data[1];
            short cmd = BitConverter.ToInt16(cmdBytes, 0);

            byte[] packetData = new byte[data.Length - 2];
            for (int i = 0; i < data.Length - 2; i++)
            {
                packetData[i] = data[i + 2];
            }

            string msg = Encoding.UTF8.GetString(packetData);
            Debug.Log("receive server data:" + msg);

            // TODO handle packet
        }
    }
}
